package cn.display.pixelworksx7

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.PermissionInfo
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.PermissionChecker
import androidx.viewpager.widget.ViewPager
import cn.display.pixelworksx7.constant.GlobalData
import cn.display.pixelworksx7.data.AppConfigInfo
import cn.display.pixelworksx7.data.AppConfigInfoFile
import cn.display.pixelworksx7.databinding.ActivityMainBinding
import cn.display.pixelworksx7.receiver.ScreenListener
import cn.display.pixelworksx7.receiver.ScreenListener.ScreenStateListener
import cn.display.pixelworksx7.ui.main.SectionsPagerAdapter
import cn.display.pixelworksx7.util.IrisConfigUtil
import cn.display.pixelworksx7.util.ShellUtil
import com.google.android.material.tabs.TabLayout
import java.io.File
import java.security.Permission
import java.security.Permissions
import kotlin.streams.toList


class MainActivity : AppCompatActivity() {
    private var screenListener: ScreenListener? = null
    private lateinit var binding: ActivityMainBinding
    private val tag = "MainActivity"

    override fun onResume() {
        super.onResume()
        // 判断是否给予权限
        checkPermission() // 检测权限
    }
    fun checkPermission() {
        var thread = Thread(Runnable {
            kotlin.run {
                if (PermissionChecker.checkPermission(this, Manifest.permission.MANAGE_EXTERNAL_STORAGE,0,0,this.packageName) == -2) {
                    var intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.setData(Uri.parse("package:" + this.getPackageName()));
                    startActivity(intent);
                }
            }
        })
        thread.start()
        thread.join()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
        val viewPager: ViewPager = binding.viewPager
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = binding.tabs
        tabs.setupWithViewPager(viewPager)
        checkPermission()
        try {
//            ShellUtil.get_root(this)
            var res: Boolean = File(IrisConfigUtil.irisConfigBinFilePath).exists()
            if (!res) {
                ShellUtil.toast(this, "当前设备不存在独显芯片 正在退出")
                onDestroy()
            }
            openIrisConfigSet(res)
            screenListener = ScreenListener(this)
            screenListener!!.begin(object : ScreenStateListener {
                override fun onScreenOn() {
                    // Log.e(tag, "屏幕打开了")
                }

                override fun onScreenOff() {
                    // Log.e(tag, "屏幕关闭了")
                    if (noBreak) {
                        noBreak = false
//                        IrisConfigUtil.disableIris(resources)
                    }
                }

                override fun onUserPresent() {
                    //Log.e(tag, "解锁了")
                    if (!noBreak) {
                        noBreak = true
                        openIrisConfigSet(true)
                    }
                }
            })
        } catch (e: Exception) {
            ShellUtil.toast(this, e.message)
            onDestroy()
//            manager!!.killBackgroundProcesses(packageName)
        }
    }

    // 开启插帧相关服务
    companion object {
        public var currentSelectAppConfigInfo: AppConfigInfo? = null
        public var noBreak: Boolean = true // 标志是否不停止循环
        public var tag = "SetIrisUtil"
        fun openIrisConfigSet(isExistsIrisConfig: Boolean) {
            Thread(Runnable {
                kotlin.run {
                    IrisConfigUtil.loadIrisConfigFileParseToMap()
                    while (isExistsIrisConfig and noBreak) {
                        // ShellUtil.toast(this, noBreak.toString())
                        // 当前上层应用
                        var currentTopPackageName = ShellUtil.execCommand(
                            "dumpsys activity activities|grep topResumedActivity=|tail -n 1|cut -d \"{\" -f2|cut -d \"/\" -f1|cut -d \" \" -f3",
                            true
                        ).successMsg
                    Log.e(tag, "当前上层应用" + currentTopPackageName)
                        if (currentTopPackageName != GlobalData.lastTopPackageName) {
                            GlobalData.lastTopPackageName = currentTopPackageName;
                            if (GlobalData.irisConfigMap.containsKey(currentTopPackageName)) {
                                // 有配置
                                var paramsCommandList =
                                    GlobalData.irisConfigMap.get(currentTopPackageName)?.stream()?.map { it ->
                                        IrisConfigUtil.irisConfigBinFilePath + " " + it
                                    }?.toList()
                            Log.w(tag, "有配置" + paramsCommandList.toString())
                                if (paramsCommandList != null) {
                                    IrisConfigUtil.disableIris()
                                    ShellUtil.execCommand(paramsCommandList.toTypedArray(), true)
                                }
                            } else if (!GlobalData.irisConfigMap.containsKey(currentTopPackageName)) {
                                Log.e(IrisConfigUtil.tag,"关闭插帧")
                                IrisConfigUtil.disableIris()
                            }
                        }
                    if (currentTopPackageName.trim().equals("")) {
                        break
                    }
//                    if (currentTopPackageName.indexOf("game")!=-1) {
//                        Thread.sleep(60000)
//                    } else {
//                        Thread.sleep(2500)
//                    }
                        Thread.sleep(1500)
                    }
                }
            }).start()
        }
    }
}
